from flask import Blueprint, request
from flask_jwt_extended import jwt_required

from models import *
from json import dumps, loads

record_bp = Blueprint('record_bp', __name__)


@record_bp.route('/api/record', methods=['GET'])
@jwt_required(refresh=True)
def record_():
    page_record_num = 20

    def timeformat(time_str):
        if time_str is None:
            return None
        return time_str.strftime('%Y-%m-%d %H:%M:%S')

    result = {"records": [], "haveNext": True}
    page = int(request.args.get('page', default='0'))  # 从0开始，每页10个
    state_ = request.args.get('state', default='')
    if state_ == '':
        this_page = DeviceBorrow.query.order_by(DeviceBorrow.id.desc()).limit(page_record_num).offset(
            page * page_record_num).all()
    else:
        this_page = DeviceBorrow.query.filter_by(state=state_).order_by(DeviceBorrow.id.desc()).limit(
            page_record_num).offset(page * page_record_num).all()
    if len(this_page) < page_record_num:
        result["haveNext"] = False
    for i in this_page:
        info = {
            'id': i.id,
            'name': i.name,
            'identity': i.identity,
            'phone_number': i.phone_number,
            'reason_type': i.reason_type,
            'reason_name': i.reason_name,
            'device': i.device,
            'return_device': i.return_device,
            'state': i.state,
            'receive_time': timeformat(i.receive_time),
            'actual_receive_time': timeformat(i.actual_receive_time),
            'return_time': timeformat(i.return_time),
            'actual_return_time': timeformat(i.actual_return_time),
            'note': i.note,
            'lenter': i.lenter
        }
        result["records"].append(info)
    return result


@record_bp.route('/api/record_update', methods=['POST'])
@jwt_required(refresh=True)
def approve():
    """
    id 是必填项
    {
        "id": 1,
        "device": {
            "相机类": {
                "松下4K电池":[1, 2, 3, 4],
            },
            "存储类": {
                "Panasonic 64G": [1, 2, 3, 4]
            }
        },
        "state": "归还",
        "actual_receive_time": "2022-02-24T13:42:05",
        "actual_return_time": "2022-02-24T13:42:05",
        "note": "备注信息",
        "lenter": "王新昀"
    }
    :return:
    """
    jsonData = request.json
    record = DeviceBorrow.query.filter_by(id=jsonData["id"]).first()
    device_category_in_record = loads(record.device)
    device_category = jsonData["device"]
    if "actual_receive_time" in jsonData:
        record.actual_receive_time = jsonData['actual_receive_time']
    if "actual_return_time" in jsonData:
        record.actual_return_time = jsonData['actual_return_time']
    if "lenter" in jsonData:
        record.lenter = jsonData['lenter']
    if 'state' in jsonData:
        record.state = jsonData['state']
    else:
        jsonData['state'] = record.state

    sql_mid = ""
    sqlStrCandition = "OR (name='%s' and ID in %s)"
    sqlStrTail = ")"
    going_to_del_category = []
    for category in device_category:
        going_to_del_name = []
        for name in device_category[category]:
            this_device = device_category[category][name]
            if len(this_device) == 0:
                going_to_del_name.append(name)
                continue
            for i in this_device:
                if type(i) is not int:
                    print(type(i))
                    db.session.rollback()
                    return "Forbidden", 400
            range_str = str(tuple(this_device)) if len(this_device) != 1 else "(%d)" % this_device[0]
            if ')' not in name:
                sql_mid += sqlStrCandition % (name, range_str)
            else:
                db.session.rollback()
                return "Forbidden", 400
        for i in going_to_del_name:
            device_category[category].pop(i)
        if len(device_category[category]) == 0:
            going_to_del_category.append(category)
    for i in going_to_del_category:
        device_category.pop(i)

    if jsonData['state'] == '归还' or jsonData['state'] == '部分还回':
        sqlStrHead = "update DeviceStatus set state='在库' where state='借出' AND (FALSE "
        db.session.execute(sqlStrHead + sql_mid + sqlStrTail)
        record.return_device = dumps(device_category, ensure_ascii=False)
        if device_category == device_category_in_record:
            record.state = '归还'
        else:
            record.state = '部分还回'
        return '处理成功，记得通知借用者哦'

    if jsonData['state'] == '驳回':
        sqlStrHead = "update DeviceStatus set state='在库' where state='预定' AND (FALSE "
        db.session.execute(sqlStrHead + sql_mid + sqlStrTail)
        return '处理成功，记得通知借用者哦'

    record.device = dumps(device_category, ensure_ascii=False)
    sqlStrHead = "select name, id from DeviceStatus where (state!='预定' and state!='在库') AND (FALSE "
    sql_result = db.session.execute(sqlStrHead + sql_mid + sqlStrTail)
    result = [row[0] for row in sql_result]
    if len(result) != 0:
        msg = ""
        for i in result:
            msg += i[0] + " " + str(i[1]) + "号、"
        db.session.rollback()
        return msg + "不在仓库中", 400

    if jsonData['state'] == '未处理' or jsonData['state'] == '待取':
        sqlStrHead = "update DeviceStatus set state='预定' where state='在库' AND (FALSE "
        db.session.execute(sqlStrHead + sql_mid + sqlStrTail)

    if jsonData['state'] == '借出':
        sqlStrHead = "update DeviceStatus set state='借出' where (state='在库' OR state='预定') AND (FALSE "
        db.session.execute(sqlStrHead + sql_mid + sqlStrTail)
    return '提交成功'
